package com.one.blocks.security.authc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.blocks.common.response.ResponseHelper;
import com.one.blocks.security.authc.rememberme.TokenService;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-10-19 11:29:51
 */
public class RestLoginSuccessHandler implements AuthenticationSuccessHandler {

    private final TokenService accessService;

    private final ObjectMapper objectMapper;

    public RestLoginSuccessHandler(TokenService accessService, ObjectMapper objectMapper) {
        this.accessService = accessService;
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = accessService.save((UserDetails) authentication.getDetails());

        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        String resBody = objectMapper.writeValueAsString(ResponseHelper.success(token));
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(resBody);
            printWriter.flush();
        }
    }
}
